package com.xzp.gkrpc.server;

import com.xzp.gkrpc.Request;
import com.xzp.gkrpc.ServiceDescriptor;
import com.xzp.gkrpc.common.utils.ReflectionUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;


import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Data
public class ServiceManager {
    private Map<ServiceDescriptor, ServiceInstance> service;
    public ServiceManager(){
        this.service = new ConcurrentHashMap<>();
    }

    /**
     *  将一个类的服务注册到service上。
     * @param interfaceClass 类
     * @param bean 类的一个实例 这里可以将bean设置为单例
     * @param <T> 类型
     */
    public <T> void register(Class<T> interfaceClass, T bean){
        // 获取所有public方法
        Method[] methods = ReflectionUtils.getPublicMethod(interfaceClass);
        // 把所有方法，实例 构成的ServiceDescriptor注册到Map上
        for(Method method: methods){
            ServiceInstance serviceInstance = new ServiceInstance(bean, method);
            ServiceDescriptor descriptor = ServiceDescriptor.from(interfaceClass, method);
            service.put(descriptor, serviceInstance);
            log.info("register service-- {}:{}", bean.getClass(), method);
        }
    }

    /**
     * 根据Request中的ServiceDescriptor去查找ServiceInstance
     * @param request
     * @return
     */
    public ServiceInstance lookup(Request request){
        ServiceDescriptor descriptor = request.getService();
        log.info("lookup service {} -- ", descriptor);
        System.out.println(service);
        return service.get(descriptor);
    }
}
